Since all stack operations rely on manipulating the `top` index, the most straightforward implementation utilizes a fixed-size array.
- This approach requires pre-defining a maximum capacity, denoted by n.
- In an array-based stack, the top index serves as the single point of access, ensuring the FILO principle is maintained.
- An empty stack is conventionally represented by setting the
toppointer to -1. - To prevent memory errors, the implementation must enforce boundary condition checks:
- Underflow: Checks if the stack is empty before a
poporpeekoperation (top == -1). - Overflow: Checks if the stack is full before a
pushoperation (top == n - 1).
- Underflow: Checks if the stack is empty before a
Array-Based Stack Conditions
| Condition | Description | `top` Value |
|---|---|---|
| Empty (Underflow) | Cannot `pop` or `peek`. | $top = -1$ |
| Partially Full | All operations are valid. | $0 \le top < n-1$ |
| Full (Overflow) | Cannot `push`. | $top = n-1$ |